<?php
// +----------------------------------------------------------------------
// | Description: 客户
// +----------------------------------------------------------------------
// | Author:  Zl
// +----------------------------------------------------------------------
namespace app\crm\model;

use app\admin\model\User;
use app\common\traits\ActionRecordTrait;
use think\facade\Db;
use app\admin\model\Common;
use think\response\Json;


use app\admin\controller\ApiCommon;


use app\crm\model\TransferShop;



class OutaddcustomerModel extends Common
{
    use ActionRecordTrait;
    /**
     * 为了数据库的整洁，同时又不影响Model和Controller的名称
     * 我们约定每个模块的数据表都加上相同的前缀，比如CRM模块用crm作为数据表前缀
     */
    protected $name = 'customer';

    /**
     * 列表
     * 会员在门诊和门店的消费合并，达到会员条件时，成为会员
     * 拥有数据权限:
     * 1. 门店看自己
     * 2. 后台看列表
     * @param  array $request 请求参数
     * --------------------------------------------------------------------------+
     * 目前存在的搜索条件
     * -+
     * $request                     搜索参数集
     * --+                          
     * page                      int       页码
     * limit                     int       每页的数据
     * create_time               string    客户录入的日期: ****-**-**
     * customer_name             string    客户的名称
     * sex                       int       性别: 0未知 1男 2女
     * source_id                 int       客户来源
     * effective_entry           int       进店标识: 0未知 1是 2否
     * membership_leve           int       会员等级
     * member_classification     int       客户分类
     * repair_progress           int       修复进展: 0未知 其他设置按照id
     * scar_id                   int       疤痕类型: 关联查询 -- customer_scar表
     * consumption               decimal   消费金额
     * consumption_type          int       搜索消费金额的范围: 1大于 2小于 3等于
     * age                       int       客户的年龄
     * --------------------------------------------------------------------------+
     * @return array
     */
    public function addData($request)
    {
        
        // echo "<pre>";
        // print_r($request);
        // echo "</pre>";
        // exit;

        $telephone = $request['telephone'];

        $customer_info = Db::name('customer')->where('telephone',$telephone)->select()->toArray();

        if(empty($customer_info)){

            $shopId = $request['shop_id'];
            $otc_shop_id = $request['otc_shop_id'][1];
            $data = [
                'shop_id'               => $shopId,
                'otc_shop_id'           => $otc_shop_id,
                'customer_name'         => trim($request['customer_name']),
                'telephone'             => isset($request['telephone']) ? intval($request['telephone']) : '',
                'source_id'             => isset($request['source_id']) ? intval($request['source_id']) : 0,
                'creator_id'            => $this->staffId($request['shop_id']),
                'operator'              => $this->staffId($request['shop_id']),
                'status'                => '1',
                'repair_progress'       => '57',
                'create_time'           => time(),
                'update_time'           => time(),
                'lian_xi_ren'           => trim($request['lian_xi_ren']),
            ];

            // echo "<pre>";
            // print_r($data);
            // echo "</pre>";
            // exit;

            try {
                $customerId = Db::name('customer')->insertGetId($data);

                if ($customerId) {
                    
                    $insertAll = [
                        'customer_setting_id_type'     => $request['type_id'],
                        'customer_setting_id_position' => $request['position_id'],
                        'customer_id'                  => $customerId,
                    ];

                    // echo "<pre>";
                    // print_r($insertAll);
                    // echo "</pre>";

                    $scarID = Db::name('customer_scar')->insertGetId($insertAll);
                    
                    // 存储客户的余额信息
                    $customer_balanceAll = [
                        [
                            'shop_id'       => $shopId,
                            'customer_id'   => $customerId,
                            'balance_category_id'   => 1,
                        ],
                        [
                            'shop_id'       => $shopId,
                            'customer_id'   => $customerId,
                            'balance_category_id'   => 2,
                        ],
                        [
                            'shop_id'       => $shopId,
                            'customer_id'   => $customerId,
                            'balance_category_id'   => 3,
                        ],
                        [
                            'shop_id'       => $shopId,
                            'customer_id'   => $customerId,
                            'balance_category_id'   => 24,
                        ]
                    ];

                    // echo "<pre>";
                    // print_r($customer_balanceAll);
                    // echo "</pre>";

                    
                    Db::name('customer_balance')->insertAll($customer_balanceAll);
                    

                    // 发送短信
                    $shop_info = Db::name('shop')->where('shop_id',$shopId)->find();

                    $sendsmsData = [
                        'group'   => $shop_info['shop_name'],
                        'address' => $shop_info['address'],
                        'tel'     => $shop_info['shop_phone'],
                    ];

                    $senMsge = new TransferShop();
					$senMsge->sendSms($telephone,$sendsmsData);

                    // echo "发送成功了么";

                }

                $this->error    = '添加成功';
                return true;

            } catch (\Exception $e) {
                $this->error    = '添加失败';
                return false;
            }
            
                
                

            

        }else{
            $shop_info = Db::name('shop')->where('shop_id',$customer_info[0]['shop_id'])->select()->toArray();
            $this->error = '手机号已存在无法创建客户，当前客户在【'.$shop_info[0]['shop_name'].'】门店';
            return false;
        }
        
    }

    public function staffId($shop_id)
    {
        // 郑州市场
        $staff['73782774834649'] = '396'; // 大学路
        $staff['73782774813357'] = '454'; // 文化路
        $staff['73782774896742'] = '965'; // 天明路
        $staff['73782774813542'] = '395'; // 航海路
        $staff['73782774822370'] = '390'; // 玉凤路
        $staff['73782774880422'] = '977'; // 建设西路
        $staff['73782774859952'] = '394'; // 郑州万达
        $staff['73782774881835'] = '393'; // 中医院

        $staff['73782774973465'] = '372'; // 杨家坪
        $staff['73782774939196'] = '168'; // 南坪店
        $staff['73782774982464'] = '16'; // 江北店
        $staff['73782774991693'] = '21'; // 重庆门诊

        // 哈尔滨
        $staff['73782775133028'] = '35'; // 爱建店

        // 长春
        $staff['73782775102252'] = '370'; // 红旗街店

        // 沈阳
        $staff['73782775013838'] = '223'; // 中街店

        // 天津
        $staff['73782775074894'] = '214'; // 长江道

        // 北京
        $staff['73782775492343'] = '387'; // 银河店

        // 石家庄
        $staff['73782775382480'] = '251'; // 新百店
        $staff['73782775377728'] = '256'; // 石家庄门诊

        // 太原
        $staff['73782774791259'] = '5'; // 体育路

        // 西安
        $staff['73782775132896'] = '274'; // 吉祥店
        $staff['73782775206631'] = '288'; // 西安门诊

        // 济南
        $staff['73782775246614'] = '73'; // 大关店
        $staff['73782775392774'] = '364'; // 济南门诊

        // 成都
        $staff['73782774988622'] = '181'; // 总府店
        $staff['73782775085647'] = '775'; // 成都门诊

        // 昆明
        $staff['73782775140871'] = '191'; // 金碧店
        $staff['73782775131388'] = '83'; // 昆明门诊

        // 南宁
        $staff['73782775241316'] = '206'; // 同开店

        return $staff[$shop_id];
    }

    public function serviceCards($id){
        $serviceCards = [];

        array_push($serviceCards,[]);
        array_push($serviceCards,[['id'=>615,'name'=>'水漾补水小套','num'=>3]]);
        array_push($serviceCards,[['id'=>613,'name'=>'三膜清洁小套','num'=>3]]);
        array_push($serviceCards,[['id'=>148,'name'=>'童颜水娃娃','num'=>3]]);
        array_push($serviceCards,[['id'=>151,'name'=>'高能小粉瓶','num'=>1]]);
        array_push($serviceCards,[['id'=>151,'name'=>'高能小粉瓶','num'=>1],['id'=>148,'name'=>'童颜水娃娃','num'=>3]]);
        array_push($serviceCards,[['id'=>151,'name'=>'高能小粉瓶','num'=>6],['id'=>148,'name'=>'童颜水娃娃','num'=>10]]);

        array_push($serviceCards,[['id'=>477,'name'=>'光子嫩肤','num'=>1]]);
        array_push($serviceCards,[['id'=>151,'name'=>'高能小粉瓶','num'=>1]]);
        array_push($serviceCards,[['id'=>496,'name'=>'7D聚拉提','num'=>1]]);
        array_push($serviceCards,[['id'=>478,'name'=>'全面部超声刀','num'=>1],['id'=>473,'name'=>'美白光','num'=>1]]);

        return $serviceCards[$id];
    }


    // 重庆市场
    public function addDataChongQing($request)
    {

        // echo "<pre>";
        // print_r($request);
        // echo "</pre>";
        $scarInfo = $request['type_id'] ?? [];

        $scarList = [];

        if($scarInfo){

            foreach ($scarInfo as $key => $value) {

                $one = [];

                $item = explode('-',$value);

                $one['type_id'] = $item[0];

                $one['position_id'] = $item[1];

                array_push($scarList,$one);

            }
        }

        // echo "<pre>";
        // print_r($scarList);
        // echo "</pre>";
        // exit;

        $telephone = $request['telephone'];

        $customer_info = Db::name('customer')->where('telephone',$telephone)->select()->toArray();

        if(empty($customer_info)){

            $shopId = $request['shop_id'];
            $data = [
                'shop_id'               => $shopId,
                'customer_name'         => trim($request['customer_name']),
                'telephone'             => isset($request['telephone']) ? intval($request['telephone']) : '',
                'source_id'             => isset($request['source_id']) ? intval($request['source_id']) : 0,
                'creator_id'            => $this->staffId($request['shop_id']),
                'operator'              => $this->staffId($request['shop_id']),
                'status'                => '1',
                'repair_progress'       => '57',
                'create_time'           => time(),
                'update_time'           => time(),
                'remarks'               => trim($request['code']),
            ];

            try {
                $customerId = Db::name('customer')->insertGetId($data);

                if ($customerId) {
                    
                    foreach ($scarList as $key => $value) {

                        $insertAll = [
                            'customer_setting_id_type'     => $value['type_id'],
                            'customer_setting_id_position' => $value['position_id'],
                            'customer_id'                  => $customerId,
                        ];
    
                        $scarID = Db::name('customer_scar')->insertGetId($insertAll);
                        
                    }

                    
                    
                    // 存储客户的余额信息
                    $customer_balanceAll = [
                        [
                            'shop_id'       => $shopId,
                            'customer_id'   => $customerId,
                            'balance_category_id'   => 1,
                        ],
                        [
                            'shop_id'       => $shopId,
                            'customer_id'   => $customerId,
                            'balance_category_id'   => 2,
                        ],
                        [
                            'shop_id'       => $shopId,
                            'customer_id'   => $customerId,
                            'balance_category_id'   => 3,
                        ],
                        [
                            'shop_id'       => $shopId,
                            'customer_id'   => $customerId,
                            'balance_category_id'   => 24,
                        ]
                    ];

                    // echo "<pre>";
                    // print_r($customer_balanceAll);
                    // echo "</pre>";

                    
                    Db::name('customer_balance')->insertAll($customer_balanceAll);
                    

                    // // 发送短信
                    // $shop_info = Db::name('shop')->where('shop_id',$shopId)->find();

                    // $sendsmsData = [
                    //     'group'   => $shop_info['shop_name'],
                    //     'address' => $shop_info['address'],
                    //     'tel'     => $shop_info['shop_phone'],
                    // ];

                    // $senMsge = new TransferShop();
					// $senMsge->sendSms($telephone,$sendsmsData);

                    // echo "发送成功了么";

                }

                $this->error    = '添加成功';
                return [
                    'name'  => $request['customer_name'],
                    'phone' => $request['telephone'],
                    'code'  => $request['code'],
                ];

            } catch (\Exception $e) {
                $this->error    = '添加失败';
                return false;
            }
            

        }else{

            $shop_info = Db::name('shop')->where('shop_id',$customer_info[0]['shop_id'])->select()->toArray();

            $this->error = '手机号已存在无法创建客户，当前客户在【'.$shop_info[0]['shop_name'].'】门店';

            return false;

            // $this->error    = '添加成功';
            // return [
            //     'name'  => $request['customer_name'],
            //     'phone' => $request['telephone'],
            //     'code'  => $request['code'],
            // ];

        }

    }

    // 疤愈
    public function addDataBaYu($request){

        $name = $request['username'] ?? '';
        $telephone = $request['phone'] ?? '';
        if (!$name || !$telephone) {
            $this->error = '请完善用户信息';
            return [];
        }

        $shop_id = $request['service_center'] ?? '';
        if (!$shop_id) {
            $this->error = '请选择门店信息';
            return [];
        }

        // $customer_info = Db::name('customer')->where('telephone',$telephone)->select()->toArray();

        if(empty($customer_info)){
            $data = [
                'shop_id'               => $shop_id,
                'customer_name'         => trim($name),
                'telephone'             => isset($telephone) ? intval($telephone) : '',
                'source_id'             => '608',
                'creator_id'            => $this->staffId($shop_id),
                'operator'              => $this->staffId($shop_id),
                'status'                => '1',
                'repair_progress'       => '57',
                'create_time'           => time(),
                'update_time'           => time(),
                'lian_xi_ren'           => '',
            ];

            // try {
                // $customerId = Db::name('customer')->insertGetId($data);

                $scarInfo = explode(',',$request['scar']);

                $customerId = '141222';
                if ($customerId) {
                    
                    $insertAll = [
                        'customer_setting_id_type'     => $scarInfo[0],
                        'customer_setting_id_position' => $scarInfo[1],
                        'customer_id'                  => $customerId,
                    ];

                    // echo "<pre>";
                    // print_r($insertAll);
                    // echo "</pre>";

                    // $scarID = Db::name('customer_scar')->insertGetId($insertAll);
                    
                    // 存储客户的余额信息
                    $customer_balanceAll = [
                        [
                            'shop_id'       => $shop_id,
                            'customer_id'   => $customerId,
                            'balance_category_id'   => 1,
                        ],
                        [
                            'shop_id'       => $shop_id,
                            'customer_id'   => $customerId,
                            'balance_category_id'   => 2,
                        ],
                        [
                            'shop_id'       => $shop_id,
                            'customer_id'   => $customerId,
                            'balance_category_id'   => 3,
                        ],
                        [
                            'shop_id'       => $shop_id,
                            'customer_id'   => $customerId,
                            'balance_category_id'   => 24,
                        ]
                    ];

                    // echo "<pre>";
                    // print_r($customer_balanceAll);
                    // echo "</pre>";

                    
                    // Db::name('customer_balance')->insertAll($customer_balanceAll);

                    // 发放卡项
                    $project1 = $this->serviceCards($request['project-1'] ?? 0);
                    $project2 = $this->serviceCards($request['project-2'] ?? 0);
                    $project3 = $this->serviceCards($request['project-3'] ?? 0);

                    $serviceList = [];

                    if($project1){
                        foreach ($project1 as $key => $value) {
                            array_push($serviceList,$value);
                        }
                    }
                    if($project2){
                        foreach ($project2 as $key => $value) {
                            array_push($serviceList,$value);
                        }
                    }
                    if($project3){
                        foreach ($project3 as $key => $value) {
                            array_push($serviceList,$value);
                        }
                    }
                    
                    $serviceDataAll = [];
                    foreach ($serviceList as $key => $value) {
                        $goodInfo = Db::name('shop_goods')->where("id",$value['id'])->find();

                        $oneService = [];

                        $oneService['name']    = $value['name'];  //服务名称

                        $oneService['num']     = $value['num'];   // 必填--服务类型：1按期2按次

                        $oneService['shop_id'] = $shop_id;    // 店铺id

                        $oneService['customer_id']  = $customerId;   // 必填--客户id

                        $oneService['service_type'] = '2';   // 必填--服务类型：1按期2按次

                        $oneService['kk_user_id']   = $this->staffId($shop_id);     // 开卡人id

                        $oneService['goods_id']     = $value['id'];       // 开卡金额

                        $oneService['category_id']  = $goodInfo['category_id'];       // 开卡金额

                        array_push($serviceDataAll,$oneService);
                    }

                    

                    $customerModel = new \app\crm\model\Customer();

                    $customerModel->addCustomService($customerId,$serviceDataAll);

                    echo "<pre>";
                    print_r($serviceDataAll);
                    echo "</pre>";
                    exit;

                    // // 发送短信
                    // $shop_info = Db::name('shop')->where('shop_id',$shopId)->find();

                    // $sendsmsData = [
                    //     'group'   => $shop_info['shop_name'],
                    //     'address' => $shop_info['address'],
                    //     'tel'     => $shop_info['shop_phone'],
                    // ];

                    // $senMsge = new TransferShop();
					// $senMsge->sendSms($telephone,$sendsmsData);

                    // echo "发送成功了么";

                }

                $this->error    = '添加成功';
                return true;

            // } catch (\Exception $e) {
            //     $this->error    = '添加失败';
            //     return false;
            // }

        }else{
            $shop_info = Db::name('shop')->where('shop_id',$customer_info[0]['shop_id'])->select()->toArray();
            $this->error = '手机号已存在无法创建客户，当前客户在【'.$shop_info[0]['shop_name'].'】门店';
            return false;
        }
    }
}